package com.tiger.admin.interceptor;


import com.auth0.jwt.interfaces.Claim;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.admin.Db;
import com.tiger.cache.RedisService;
import com.tiger.common.Jwt;
import com.tiger.db.entity.Member;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;

import java.util.Map;

@Component
public class AuthInterceptor implements HandlerInterceptor{


    private final Db db;
    private final RedisService redisService;

    @Autowired
    public AuthInterceptor(Db db, RedisService redisService) {
        this.db = db;
        this.redisService = redisService;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        System.out.println("进入拦截器1");

        String patternPath = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        System.out.println(patternPath);

        try {

            // 手动获取Environment对象
            Environment environment = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getServletContext())
                    .getEnvironment();


            String token = request.getHeader(environment.getProperty("AuthTokenName"));


            if(token == null) return false;

            // 手动获取ApplicationContext
            ApplicationContext context = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getServletContext());

            Jwt jwt = context.getBean(Jwt.class);

            //验证token
            Map<String, Claim> res = jwt.verifyToken(token);

            if(res == null) return  false;

            Map<String, Object> data = res.get("data").asMap();

            if(data == null) return false;



            if(data.get("k") == null) return false;

            if(redisService.template.opsForValue().get(data.get("salt") + ":" + data.get("k")) == null) return false;


            Long memberId = Long.valueOf((Integer) data.get("k"));

            Member member = db.member.getOne(new LambdaQueryWrapper<Member>().select(Member::isEnable, Member::getId).eq(Member::getId, memberId));



            if(member == null || !member.isEnable()) {
                return false;
            }

            request.setAttribute("memberId", memberId);
            request.setAttribute("salt", data.get("salt"));

            return true;
        } catch (Exception e) {
            System.out.println("拦截器异常");
            // 处理所有类型的异常的代码块
            System.out.println("发生异常：" + e.getMessage());
        }



        return false;
    }

}
